package com.sanda.androidcourse.chapter07;

import android.Manifest;
import android.content.ContentResolver;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.widget.TextView;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;

import com.sanda.androidcourse.R;

public class PhoneContactActivity extends AppCompatActivity {


    private TextView txtContactView;

    // 使用最新的 ActivityResult API 替代 onRequestPermissionsResult()
    private final ActivityResultLauncher<String> requestPermissionLauncher =
            registerForActivityResult(new ActivityResultContracts.RequestPermission(), isGranted -> {
                if (isGranted) {
                    readContacts(); // 权限被授予，读取通讯录
                } else {
                    txtContactView.setText("Permission Denied");
                }
            });

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_phone_contact);
        txtContactView = findViewById(R.id.txt_contact);
        // 检查权限
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS) == PackageManager.PERMISSION_GRANTED) {
            readContacts(); // 已授权，直接读取通讯录
        } else {
            requestPermissionLauncher.launch(Manifest.permission.READ_CONTACTS); // 请求权限
        }
    }

    private void readContacts() {
        StringBuilder contacts = new StringBuilder();
        ContentResolver contentResolver = getContentResolver();
        Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
        Cursor cursor = contentResolver.query(uri, new String[]{
                ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
                ContactsContract.CommonDataKinds.Phone.NUMBER
        }, null, null, null);

        if (cursor != null) {
            while (cursor.moveToNext()) {
                String name = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
                String phone = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.NUMBER));
                contacts.append(name).append(" : ").append(phone).append("\n");
            }
            cursor.close();
        }

        txtContactView.setText(contacts.toString());
    }
}